package com.example.community.service.Impl;

import com.example.community.dao.mapper.UserMapper;
import com.example.community.dao.pojo.User;
import com.example.community.service.UserService;
import com.example.community.uitls.CommunityConstant;
import com.example.community.uitls.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService, CommunityConstant {

    @Autowired
    private UserMapper userMapper;

//    public User findUserById(int id) {
//        return userMapper.selectById(id);
//    }

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public User findUserById(int UserId) {
        User user = getCache(UserId);
        if (user == null){
            user = initCache(UserId);
        }
        return user;
    }

    @Override
    public User findUserByUsername(String username) {
        return userMapper.selectByName(username);
    }

    @Override
    public User findUserByEmail(String email) {
        return userMapper.selectByEmail(email);
    }

    @Override
    public void insertUser(User user) {
        userMapper.insertUser(user);
    }

    @Override
    public void updateActivationCode(int userId, int i) {
        userMapper.updateStatus(userId,1);
    }

    @Override
    public void updateHeader(int userId, String headerUrl) {

        userMapper.updateHeader(userId,headerUrl);
        clearCache(userId);

    }

    //1.优先从缓存中查询用户信息
    private User getCache(int userId){
        String redisKey  = RedisKeyUtil.getUserKey(userId);
        return (User) redisTemplate.opsForValue().get(redisKey);
    }

    //2.取不到数据时，查询数据缓存到redis中
    private User initCache(int userId){
        User user = userMapper.selectById(userId);
        String redisKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.opsForValue().set(redisKey,user,3600, TimeUnit.SECONDS);
        return user;
    }

    //3.数据变更时清除缓存数据
    public void clearCache(int userId){
        String redisKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.delete(redisKey);
    }

    //查询用户权限的集合
    public List<? extends GrantedAuthority> getAuthorities(int userId){
        User user = userMapper.selectById(userId);
        List<GrantedAuthority> list = new ArrayList<>();
        list.add(new GrantedAuthority() {
            @Override
            public String getAuthority() {
                switch (user.getType()){
                    case 1:return AUTHORITY_ADMIN;
                    case 2:return AUTHORITY_MODERATOR;
                    default:return AUTHORITY_USER;
                }
            }
        });

        return list;
    }

}
